/**
 * 判断数据是否为空
 * @param {*} str
 */
const isBlank = function isBlank(str: any) {
  if (Object.prototype.toString.call(str) === '[object Undefined]') {
    // 空
    return true
  }
  if (
    Object.prototype.toString.call(str) === '[object String]' ||
    Object.prototype.toString.call(str) === '[object Array]'
  ) {
    // 字条串或数组
    return str.length === 0
  }
  if (Object.prototype.toString.call(str) === '[object Object]') {
    return JSON.stringify(str) === '{}'
  }
  return true
}

/**
 * 获取地址栏参数
 * @param paraName 需获取的参数名
 * @returns 返回获取参数
 */
const getUrlParam = (paraName: any) => {
  const url = document.location.toString()
  const arrObj = url.split('?')
  if (arrObj.length > 1) {
    const arrPara = arrObj[1].split('&')
    let arr
    for (let i = 0; i < arrPara.length; i++) {
      arr = arrPara[i].split('=')
      // eslint-disable-next-line eqeqeq
      if (arr != null && arr[0] == paraName) {
        return arr[1]
      }
    }
    return ''
  } else {
    return ''
  }
}

/**
 * 拼接参数到url上
 * @param url 接口地址
 * @param params 需要拼接的json
 * @returns 返回拼接好的url
 */
const mergeUrlParams = (url: string, params?: RKV<any>, str = '/') => {
  if (!params) return url
  const path = Object.keys(params).map((key) => params[key])

  return `${url}${path.join(str)}`
}

/**
 * 拼接URL参数
 * @param baseUrl 基本的URL字符串
 * @param params 参数对象，包含要拼接的键值对
 * @returns 拼接好的URL字符串
 */
const buildUrlWithParams = (baseUrl: string, params: Record<string, any>): string => {
  // 检查 baseUrl 是否以 "?" 结尾
  const hasQueryParams = baseUrl.includes('?')

  // 将参数对象转换为查询字符串
  const queryParams = Object.entries(params)
    .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
    .join('&')

  // 拼接基本 URL 和查询字符串
  const url = hasQueryParams ? `${baseUrl}&${queryParams}` : `${baseUrl}?${queryParams}`

  return url
}

/**
 * 下载文件流
 * @param data：文件流
 */
const downloadFile = (data: Blob, contentDisposition = '') => {
  const match = contentDisposition.match(/filename=(.+)$/)
  const fileName = match ? decodeURIComponent(match[1]) : '未获取到文件名.xlsx'
  const downloadUrl = window.URL.createObjectURL(new Blob([data]))
  const link = document.createElement('a')
  link.href = downloadUrl
  link.setAttribute('download', fileName)
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

/**
 *
 * @param link 链接字符串
 * @returns 返回链接名称
 */
const extractFolderNameFromLink = (link: string) => {
  const url = new URL(link)
  const pathName = url.pathname.split('/')?.pop()

  if (pathName) {
    return decodeURIComponent(pathName)
  }
  return '未获取到名称'
}

/**
 * 获取下拉数据
 * getSelectOptions<META_DATA_PARAMS.MetaEntity>(info, apiGetMetaEntityList, (item) => ({
      label: item.name,
      value: item.id
    }))
 * @param info 所需参数
 * @param apiCall 接口
 * @param transform 格式化数据
 * @returns { total: number; datas: GOLBAL_PARAMS.DictInfo<T>[] }
 */
const getSelectOptions = <T>(
  info: GOLBAL_PARAMS.ListRequestData,
  apiCall: (
    info: GOLBAL_PARAMS.ListRequestData
  ) => Promise<ResponseKVData<GOLBAL_PARAMS.ListData<T>>>,
  transform: (item: T) => GOLBAL_PARAMS.DictInfo<T>
) => {
  return new Promise<GOLBAL_PARAMS.ListData<GOLBAL_PARAMS.DictInfo<T>>>(async (resolve) => {
    const res = await apiCall(info)
    const data = res.data || res.responseData
    const list = data.datas || []
    resolve({
      total: data.count || 0,
      datas: list.map(transform)
    })
  })
}

export {
  isBlank,
  getUrlParam,
  mergeUrlParams,
  buildUrlWithParams,
  downloadFile,
  extractFolderNameFromLink,
  getSelectOptions
}
